<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :minHeight="20"
    okText="提交"
    @register="register"
    :title="modalTitle"
    :loading="loading"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, nextTick, ref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getequipmentinfo, getreaddownloadtags, updateItem, addItem } from '/@/api/butlerDocking/index';
  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });
  let loading = ref(false);
  let modalTitle = computed(() => {
    return `${props.info.type === 'add' ? '新建' : '编辑'}`;
  });
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'TenantCode',
      component: 'Input',
      label: '租户编码：',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入租户编码',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'DeviceCode',
      component: 'Select',
      label: '设备：',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'FullName', value: 'AssetCode', key: 'AssetCode' },
        onChange: (e) => {
          let result = deviceTypeList.filter((item) => item.AssetCode === e);
          console.log(result)
          if(result && result.length > 0 && e){
            getTagNameList(result[0].FullName)
          }
        }
      },
      rules: [
        {
          required: true,
          message: '请选择设备',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'TagName',
      component: 'Select',
      label: '点位：',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Key', key: 'Key' },
      },
      rules: [
        {
          required: true,
          message: '请选择点位',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'TriggerStuff',
      component: 'Select',
      label: '条件：',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          { label: '变化', value: 0 },
          { label: '等于', value: 1 },
        ],
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择条件');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Value',
      component: 'Input',
      label: '条件值：',
      colProps: {
        span: 24,
      },
      ifShow: ({ values }) => {
        return values.TriggerStuff && values.TriggerStuff === 1;
      },
      rules: [
        {
          required: true,
          message: '请输入条件值',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'ServerUrl',
      component: 'Input',
      label: '接口：',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入接口',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Pameter',
      component: 'Input',
      label: '参数：',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'Description',
      component: 'Input',
      label: '描述：',
      colProps: {
        span: 24,
      },
    },
  ];

  const [
    registerForm,
    { validateFields, setFieldsValue, resetFields, clearValidate, updateSchema },
  ] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const emit = defineEmits(['submitSuccess']);
  const [register] = useModal();
  let deviceTypeList = [] as any;
  let TagNameList = [];
  // 获取设备
  async function getDeviceTypes() {
    try {
      loading.value = true;

      let res = await getequipmentinfo([
        {
          AssetCode: '',
          ModelCode: '',
          TypeCode: '',
        },
      ]);

      deviceTypeList = res
      updateSchema({
        field: 'DeviceCode',
        componentProps: {
          options: deviceTypeList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 获取点位
  async function getTagNameList(code) {
    try {
      loading.value = true;

      let res = await getreaddownloadtags([code]);

      TagNameList = res
      updateSchema({
        field: 'TagName',
        componentProps: {
          options: TagNameList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  async function handleSubmint() {
    try {
      let res = await validateFields();
      if (props.info.type === 'add') {
        await addItem([res]);
      } else {
        await updateItem([{ Id: props.info.data.Id, ...res }]);
      }

      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', {});
    } catch (error: any) {
      console.log('not passing', error);
    }
  }
  // 设置可选项

  function handleVisibleChange(visible) {
    if (visible) {
      getDeviceTypes();
      nextTick(async () => {
        if (props.info.type !== 'add') {
          setFieldsValue(props.info.data);
        }

        clearValidate();
      });
    } else {
      resetFields();
    }
  }
</script>

<style lang="less" scoped>
  .slot-select {
    width: 100%;
    height: 32px;
    padding: 0 11px;
    display: flex;
    position: relative;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    cursor: pointer;
  }

  .slot-select:hover {
    border: 1px solid #1e80ff;
  }

  .slot-select-con {
    margin-right: 18px;
    line-height: 30px;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #000000d9;
    font-size: 14px;
  }

  .con-placeholder {
    color: #bfbfbf;
  }

  .icon-style {
    line-height: 30px;
    font-size: 11px;

    color: #bfbfbf;
  }

  .erro-style {
    border: 1px solid #ed6f6f !important;
  }

  .slot-select-diabled {
    background: #f5f5f5;
    cursor: not-allowed;

    .slot-select-con {
      color: rgba(0, 0, 0, 0.25);
    }
  }

  .slot-select-diabled:hover {
    border: 1px solid #d9d9d9;
  }
</style>
